package com.wing.unit.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.unit.dao.CustomerTypeDao;
import com.wing.unit.model.entity.CustomerType;
import com.wing.unit.model.request.CustomerTypeForm;
import com.wing.unit.model.response.CustomerTypeVO;
import com.wing.unit.model.response.NodeDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.shade.org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户类别-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CustomerTypeServiceImpl extends ServiceImpl<CustomerTypeDao, CustomerType> implements CustomerTypeService {
    private static long ROOT_ID=-1l;
    @Override
    public int add(CustomerTypeForm customerTypeForm) {
        //校验
        CustomerType customerType =new CustomerType();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CustomerType.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customerTypeForm, customerType, copyOptions);
        if (customerTypeForm.getParentId()!=ROOT_ID){
            CustomerType customerTypeParent = new CustomerType();
            customerTypeParent.setId(customerTypeForm.getParentId());
            customerTypeParent.setHasChild(true);
            if (customerTypeForm.getIsDeleted()){
                customerTypeParent.setHasEnableChild(true);
            }
            baseMapper.updateById(customerTypeParent);
        }
        return baseMapper.insert(customerType);
    }

    @Override
    public List<CustomerTypeVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CustomerTypeVO> pageList4app(Page page, Map<String, Object> params) {
        List<CustomerTypeVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CustomerTypeVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public int update(CustomerTypeForm customerTypeForm) {
        CustomerTypeVO customerTypeVO = baseMapper.get4appById(customerTypeForm.getId());
        if (customerTypeVO!=null){
            if (!customerTypeVO.getParentId().equals(customerTypeForm.getParentId())){
                CustomerType customerType = new CustomerType();
                BeanUtils.copyProperties(customerTypeForm,customerType);
                baseMapper.updateById(customerType);

                if (customerTypeForm.getParentId()!=ROOT_ID){
                    CustomerType parentCustomerType = new CustomerType();
                    parentCustomerType.setId(customerTypeForm.getParentId());
                    parentCustomerType.setHasChild(true);
                    if (customerTypeForm.getIsDeleted()){
                        parentCustomerType.setHasEnableChild(true);
                    }
                    baseMapper.updateById(parentCustomerType);
                }
                if (customerTypeVO.getParentId()!=ROOT_ID){
                    int count = baseMapper.selectCount(new QueryWrapper<CustomerType>().eq("parent_id",customerTypeVO.getParentId()));
                    if (count==0){
                        CustomerType customerTypeParent = new CustomerType();
                        customerTypeParent.setId(customerTypeVO.getParentId());
                        customerTypeParent.setHasChild(false);
                        baseMapper.updateById(customerTypeParent);
                    }
                    count = baseMapper.selectCount(new QueryWrapper<CustomerType>().eq("parent_id",customerTypeVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        CustomerType customerTypeParent = new CustomerType();
                        customerTypeParent.setId(customerTypeVO.getParentId());
                        customerTypeParent.setHasChild(false);
                        baseMapper.updateById(customerTypeParent);
                    }
                }
            }else{
                boolean isUpdateEnable=customerTypeVO.getIsDeleted().equals(customerTypeForm.getIsDeleted());
                CustomerType customerType = new CustomerType();
                BeanUtils.copyProperties(customerTypeForm,customerType);
                baseMapper.updateById(customerType);
                if(isUpdateEnable&&!customerTypeForm.getIsDeleted()&&customerTypeForm.getParentId()!=ROOT_ID){
                    int count = baseMapper.selectCount(new QueryWrapper<CustomerType>().eq("parent_id",customerTypeVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        CustomerType customerTypeParent = new CustomerType();
                        customerTypeParent.setId(customerTypeVO.getParentId());
                        customerTypeParent.setHasChild(false);
                        baseMapper.updateById(customerTypeParent);
                    }
                }
            }
        }
        return 0;
    }

    @Override
    @Transactional
    public int enable(Long id) {
        CustomerTypeVO customerTypeVO = baseMapper.get4appById(id);
        if(customerTypeVO!=null){
            CustomerType customerType = new CustomerType();
            customerType.setId(id);
            customerType.setIsDeleted(true);
            int updateCount=baseMapper.updateById(customerType);
            if (customerTypeVO.getParentId()!=ROOT_ID){
                CustomerType customerTypeParent = new CustomerType();
                customerTypeParent.setId(customerTypeVO.getParentId());
                customerTypeParent.setHasEnableChild(true);
                baseMapper.updateById(customerTypeParent);
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public int disable(Long id) {
        CustomerTypeVO customerTypeVO = baseMapper.get4appById(id);
        if(customerTypeVO!=null){
            CustomerType customerType = new CustomerType();
            customerType.setId(id);
            customerType.setIsDeleted(false);
            int updateCount=baseMapper.updateById(customerType);
            if (customerTypeVO.getParentId()!=ROOT_ID){
                int count = baseMapper.selectCount(new QueryWrapper<CustomerType>().eq("parent_id",customerTypeVO.getParentId()).eq("is_deleted",true));
                if(count==0){
                    CustomerType customerTypeParent = new CustomerType();
                    customerTypeParent.setId(customerTypeVO.getParentId());
                    customerTypeParent.setHasEnableChild(false);
                    baseMapper.updateById(customerTypeParent);
                }
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public JsonResult getTreeData() {
        List<CustomerTypeVO> list = baseMapper.list4app(new HashMap<>());
        Map<Long,List<NodeDataVO>> map=new HashMap<>();
        for (CustomerTypeVO typeVO:list){
            if(map.containsKey(typeVO.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(typeVO.getId().toString());
                nodeDataVO.setName(typeVO.getName());
                map.get(typeVO.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(typeVO.getId().toString());
                nodeDataVO.setName(typeVO.getName());
                tmpList.add(nodeDataVO);
                map.put(typeVO.getParentId(),tmpList);
            }
        }
        List<NodeDataVO> rootList=map.get(-1L);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    private void  constructTree(List<NodeDataVO> parentList, Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }

}
